local kuanyan = fk.CreateSkill {

  name = "fk__kuanyan",

  tags = {  },

}
local U = require "packages/utility/utility"



kuanyan:addEffect("active", {
  name = "fk__kuanyan",
  anim_type = "support",
  can_use = function (self, player, card)
    return player:usedSkillTimes(kuanyan.name, Player.HistoryPhase) == 0 and not player:isNude()
  end,
  card_num = 1,
  target_num = 1,
  card_filter = function(self, player, to_select, selected)
    return #selected == 0 and not player:prohibitDiscard(Fk:getCardById(to_select))
  end,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and to_select ~= player
  end,
  on_use = function (self, room, effect)
    local player =effect.from
    local to =effect.tos[1]
    local card = effect.cards[1]
    room:throwCard(card, kuanyan.name, player, player)
    if player.dead or to.dead then return end
    room:addTableMarkIfNeed(player, kuanyan.name, to.id)
    room:setPlayerMark(to, "fk__kuanyan_target", 1)
  end
})

kuanyan:addEffect(fk.CardUseFinished, {
  mute = true,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(kuanyan.name) and table.contains(player:getTableMark("fk__kuanyan"), target.id) and data.card.type ~= Card.TypeEquip then
      local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        local use = e.data
        return use.from == target and use.card.type == data.card.type
      end, Player.HistoryTurn)
      return #events > 0 and events[1].data == data
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("fk__kuanyan")
    room:notifySkillInvoked(player, "fk__kuanyan")
    player:drawCards(2, "fk__kuanyan")
    if not player:isNude() and not target.dead then
      local card = room:askForCard(player, 1, 1, true, "fk__kuanyan", false, ".", "#fk__kuanyan-ask:" .. target.id)
      room:moveCardTo(card, Card.PlayerHand, target, fk.ReasonGive, kuanyan.name, nil, false, player)
    end
    if not target.dead and not table.find(room.alive_players, function(p)
      return p.hp < target.hp
    end) then
      room:recover{
        who = target,
        recoverBy = player,
        skillName = "fk__kuanyan",
        num = 1,
      }
    end
  end,
})
kuanyan:addEffect(fk.TurnStart, {
  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(kuanyan.name)
  end,
  on_refresh = function(_, _, _, player)
    player.room:setPlayerMark(player, "fk__kuanyan", 0)
  end,
})

return kuanyan